import axios from "axios";
import {useUserStore} from "@/stores/userStore";
import {ElMessage} from "element-plus";
import router from "@/router";

const httpInstance = axios.create({
  baseURL:'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout:0
})

httpInstance.interceptors.request.use(config=>{
  const userStore:any = useUserStore()
  const token = userStore.userInfo.token
  if (token){
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
},e=>Promise.reject(e))

httpInstance.interceptors.response.use(res=>res.data,e=>{
  const userStore:any = useUserStore()
  if (e.response.status===401){
    console.log("token失效了")
    userStore.clearUserInfo()
    router.push("/login")
  }
  ElMessage.warning(e.response.data.message)
  return Promise.reject(e)
})

export default httpInstance